package secondriver.qiniucs.server;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONObject;

import secondriver.qiniu.QiniuCloudSession;

public class GetPutTokenServlet extends HttpServlet {

	private static final long serialVersionUID = 4975986556980453894L;

	private QiniuCloudSession qiniuCloudSession;

	@Override
	public void init() throws ServletException {
		super.init();
		qiniuCloudSession = QiniuCloudSession.build("qiniu.properties");
	}

	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		resp.setContentType("application/json;charset=UTF-8");
		resp.setCharacterEncoding("UTF-8");
		try {
			String token = qiniuCloudSession.getUpToken();
			resp.getWriter().write(new Result(Result.OK, token).toString());

		} catch (Exception e) {
			resp.getWriter().write(new Result(Result.ERROR, "").toString());
		}
		resp.flushBuffer();
	}

	public class Result {
		static final int OK = 1;
		static final int ERROR = -1;

		public Result(int code, String token) {
			this.code = code;
			this.token = token;
		}

		private int code;
		private String token;

		public int getCode() {
			return code;
		}

		public void setCode(int code) {
			this.code = code;
		}

		public String getToken() {
			return token;
		}

		public void setToken(String token) {
			this.token = token;
		}

		@Override
		public String toString() {
			return new JSONObject(this).toString();
		}
	}
}
